<?php

namespace app\admin\controller\warehouse;

use app\admin\model\Item;
use app\common\controller\Backend;
use app\admin\model\InventoryItemInfo;
use app\admin\model\inventory\Lists;
use app\admin\model\out\OutInventoryAddr;
use app\admin\model\out\OutInventoryDetail;
use app\admin\model\Warehouse;
use think\Db;
use think\Exception;
use think\Config;
use app\admin\model\GoodsItem;
use app\admin\model\inventory\InventoryList as InventoryStorage;
use app\admin\model\out\OutInventory as OutOfStock;
use app\admin\model\Logistics;

/**
 * 出库记录管理
 */
class Outinventory extends Backend
{

    protected $model = null;
    protected $dataLimit = 'personal';
    protected $dataLimitField = 'uid';

    public function _initialize(){
      parent::_initialize();
      $this->model = new OutOfStock();
    }

    public function index(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            foreach($list as $key=>$value){
              $list[$key]['logistic'] = Logistics::where('logistics_code',$value['logistic_code'])->value('logistics_name');
            }

            $wms = $this->getWarehouse();
            foreach ($list as $key => $value){
                $items = $this->getOutItemsNew($value['outorderid']);

                $itemString = '';
                foreach($items as $subkey=>$subvalue){
                  $itemString = $itemString.$subvalue['itemname'].' - '.$subvalue['itemsku'].'  *  '.$subvalue['goods_count'].' \\r\\n ';
                }

                $list[$key]['items'] = $itemString;
            }
            $result = array("total" => $total, "rows" => $list,"wms"=>$wms);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getWarehouse(){
        $wmsModel = model('Warehouse');
        $wms = $wmsModel->select();
        $wms = collection($wms)->toArray();
        return $wms;
    }

    public function items(){
        $outorderid = $this->request->post('outorderid');
        if (!empty($outorderid)) {
            $items = $this->getOutItemsNew($outorderid,'total');
            $this->success("请求成功", null, $items);
        }else{
            $this->success("网络异常，稍后重试！", null);
        }
    }


    public function getOutItemsNew($outorderid){
      $OutInventoryDetailModel = new \app\admin\model\out\OutInventoryDetail();
      $outDetail = $OutInventoryDetailModel->where(['out_orderno'=>$outorderid])->select();
      return $outDetail;
    }



    public function delete($ids=NULL){
      if ($this->request->isPost()) {
        //1.删除主记录表 2.删除t_inventory_item_info 3.删除t_out_inventory_addr 

        try {
          
          $outInventory = new \app\admin\model\out\Inventory;
          $outItem = $outInventory->where('id',$ids)->find();

          if(intval($outItem['status'])>1){
            $this->error('非待审核状态下的出库单不允许删除!');
            return;
          }
          
          Db::startTrans();

          $outInventoryDetail = new OutInventoryDetail;
        

          $outInventory->where('id',$ids)->delete(); //删除主记录 t_out_inventory

          $outInventoryDetail->where('out_orderno',$outItem['outorderid'])->delete(); //删除t_out_inventory_detail

          Db::commit();
          $this->success('删除成功!');
        } catch (\think\exception\PDOException $e) {
          $this->error($e->getMessage());
        } catch (\think\Exception $e) {
          $this->error($e->getMessage());
        }

      }
    }

    public function detail($ids=Null){

      $outWareHouseModel = new \app\admin\model\out\Inventory;
      $OutInventoryDetail = new OutInventoryDetail;
      $outWareHouseRecord = $outWareHouseModel->where('id',$ids)->find();

      $outInventoryItemRecord = $OutInventoryDetail->where('out_orderno',$outWareHouseRecord['outorderid'])->select();
      $items = collection($outInventoryItemRecord)->toArray();


      $outInventoryAddress = [];
      $outInventoryAddress['recipients'] = $items[0]['recipients'];
      $outInventoryAddress['mobile'] = $items[0]['mobile'];
      $outInventoryAddress['company'] = $items[0]['company'];
      $outInventoryAddress['state'] = $items[0]['state'];
      $outInventoryAddress['province'] = $items[0]['province'];
      $outInventoryAddress['city'] = $items[0]['city'];
      $outInventoryAddress['postcode'] = $items[0]['postcode'];
      $outInventoryAddress['addressone'] = $items[0]['addressone'];
      $outInventoryAddress['addresstwo'] = $items[0]['addresstwo'];


      $this->view->assign("outItemAddress", $outInventoryAddress);

      // $this->view->assign("global",$global);
      $this->view->assign("items", $items);

      // $this->view->assign("wms", $wms);
      return $this->view->fetch();
    }

    public function edit($ids=NULL){

      if ($this->request->isPost()) {
        $params = $this->request->post("row/a");
        if ($params) {
            try {
                //判断是否存在商品空数量
                foreach ($params['itemnum'] as $item){
                  if($item<1){
                      $this->error('请填写出库商品数量');
                  }
                }

                Db::startTrans();

                if ($params['outOrderId']){
                  $outInventory = new \app\admin\model\out\Inventory;

                  $outInventoryStatus = $outInventory->where('outorderid', $params['outOrderId'])->column('status')[0];
                  if (intval($outInventoryStatus)>1){
                    $this->error('非待审核状态下的出库单不允许编辑!');
                    return;
                  }

                  $warehouseModel = new Warehouse();
                  $warehouseId = $warehouseModel->where(['code'=>$params['warehouse_code']])->column('id')[0];

                  $inData['warehouse_code'] = $params['warehouse_code'];
                  $inData['warehouseid'] = $warehouseId;
                  $inData['file'] = $params['file'];
                  $inData['remark'] = $params['remark'];
                  $inData['orderid'] = $params['orderid'];
                  $inData[$this->dataLimitField] = $this->auth->aid;
                  $inData['logistic_code'] = $params['logistic_code'];
                  $outInventory->save($inData,['outorderid' => $params['outOrderId']]);


                  $outid = $outInventory->where('outorderid',$params['outOrderId'])->column('id')[0];
                  //先删除，再添加
                  $OutInventoryDetail = new OutInventoryDetail;
                  $OutInventoryDetail->where('out_orderno',$params['outOrderId'])->delete(); 
                  
                  for($i=0;$i< count($params['itemid']);$i++){

                    $data['id'] = \newId();
                    $data['itemsku'] = $params['itemsku'][$i];
                    $data['itemid'] = $params['itemid'][$i];
                    $data['itemname'] = $params['itemname'][$i];
                    $data['orderid'] = $params['orderid'];//关联的平台订单号

                    $data['goods_count'] = $params['itemnum'][$i]; //申请出库数
                    $data['sw_count'] = 0; //已出库数
                    $data['left_count'] = $params['itemnum'][$i]; //未出库数

                    $data['outid'] = $outid;
                    $data['out_orderno'] = $params['outOrderId'];
                    $data['warehouseid'] = $warehouseId;
                    $data['warehouse_code'] = $params['warehouse_code'];

                    // $data['recipients']= $params['recipients'];
                    $data['first_name']= $params['firstName'];
                    $data['last_name']= $params['lastName'];
                    $data['mobile']= $params['mobile'];
                    $data['company']= $params['company'];
                    $data['state']= $params['state'];
                    $data['province']= $params['province'];
                    $data['city']= $params['city'];
                    $data['postcode']= $params['postcode'];
                    $data['addressone']= $params['addressone'];
                    $data['addresstwo']= $params['addresstwo'];

                    $rsItem = $OutInventoryDetail->isUpdate(false)->save($data);

                    if($rsItem === false){
                        Db::rollback();
                        $this->error('出库申请修改失败，请重试');
                    }
                }
                Db::commit();
                $this->success();

                }
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
              // $this->error('出库申请修改失败，请联系管理员');
            } catch (\think\Exception $e) {
              // $this->error('出库申请修改失败，请联系管理员');
                $this->error($e->getMessage());
            }
        }
        $this->error(__('Parameter %s can not be empty', ''));
        return;
      }

      $outWareHouseModel = new \app\admin\model\out\Inventory;
      // $InInventoryItemModel = new InventoryItemInfo;
      $OutInventoryDetail = new OutInventoryDetail;
      $outWareHouseRecord = $outWareHouseModel->where('id',$ids)->find();
      $outInventoryItemRecord = $OutInventoryDetail->where('out_orderno',$outWareHouseRecord['outorderid'])->select();
      // $userinfo = $this->auth->getUserInfo();
      $goodsModel = new GoodsItem;
      $InventoryStorageModel = new InventoryStorage();
      $itemModel = new Item;

      $items = [];
      foreach($outInventoryItemRecord as $key=>$value){
        $goodsid = $goodsModel->where('code',$value['itemsku'])->value('id');
        $itemRecord = $itemModel->where('sku',$value['itemsku'])->find();
        $item = [];
        $item['itemname'] = $itemRecord->itemname;
        $item['itemsku'] = $itemRecord->sku;
        $item['id'] = $itemRecord->id;
        $item['goods_count'] = $value['goods_count'];
        $item['inventorycount'] = intval($InventoryStorageModel->where('goods_id',$goodsid)->value('balance_count'));
        $items[] = $item;
      }


      $condition = [];
      $condition['outorderid'] = $outWareHouseRecord['outorderid'];

      $outInventoryAddress = [];
      $outInventoryAddress['recipients'] = $outInventoryItemRecord[0]['recipients'];
      $outInventoryAddress['mobile'] = $outInventoryItemRecord[0]['mobile'];
      $outInventoryAddress['company'] = $outInventoryItemRecord[0]['company'];
      $outInventoryAddress['state'] = $outInventoryItemRecord[0]['state'];
      $outInventoryAddress['province'] = $outInventoryItemRecord[0]['province'];
      $outInventoryAddress['city'] = $outInventoryItemRecord[0]['city'];
      $outInventoryAddress['postcode'] = $outInventoryItemRecord[0]['postcode'];
      $outInventoryAddress['addressone'] = $outInventoryItemRecord[0]['addressone'];
      $outInventoryAddress['addresstwo'] = $outInventoryItemRecord[0]['addresstwo'];

      // $items = collection($outInventoryItemRecord)->toArray();
      
      $logisticList = Logistics::all();
      $logisticList = collection($logisticList)->toArray();

      $wms = $this->getWarehouse();
      $global = Config::get("global");
      $this->view->assign("global",$global);
      $this->view->assign("items", $items);
      $this->view->assign("wms", $wms);
      $this->view->assign("logisticList", $logisticList);
      $this->view->assign("outItemRecord", $outWareHouseRecord);
      $this->view->assign("outItemAddress", $outInventoryAddress);
      return $this->view->fetch();
    }


    /**
     * 导入出库
     */
    public function import() {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $PHPExcel = $PHPReader->load($filePath);
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);

        //暂时默认仓库
        $warehouseModel = new Warehouse();
        $warehouseId = $warehouseModel->where(['code'=>'1'])->column('id')[0];

        $inventoryModel = new InventoryStorage();

        Db::startTrans();
        try{
            for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                $rowNo = 1;
                unset($outAndAddr);
                for ($currentColumn = 0; $currentColumn < 16; $currentColumn++) {
                  $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                  $outAndAddr[] = is_null($val) ? '' : $val;
                }
                
                $outInventory = new OutOfStock;

                $remark = $outAndAddr[1];
                $orderid = $outAndAddr[2];
                // $goods_count = $outAndAddr[13];
                $firstName = $outAndAddr[3];//名
                $lastName = $outAndAddr[4];//姓
                $mobile = $outAndAddr[5];
                $company = $outAndAddr[6];
                $state = $outAndAddr[7];
                $province = $outAndAddr[8];
                $city = $outAndAddr[9];
                $postcode = $outAndAddr[10];
                $addressone = $outAndAddr[11];
                $addresstwo = $outAndAddr[12];
                $logistic =   sprintf("%03d", $outAndAddr[15]);//生成3位数，不足前面补0 ;//物流商

                $itemsku = $outAndAddr[13];
                $itemskuNum = $outAndAddr[14];
               
                
                $inData = [];
                //保存出库记录
                $inData['warehouse_code'] = 1;
                $inData['remark'] = $remark;
                $inData['orderid'] = $orderid;
                $outOrderId = 'OUTI' . date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                $inData['outorderid'] = $outOrderId;
                $inData['logistic_code'] = $logistic;
                $inData[$this->dataLimitField] = $this->auth->aid;
                
                $outInventory->isUpdate(false)->save($inData);

                $outid = $outInventory->getLastInsID();

                
                

                $itemskuArray = explode(",", $itemsku);
                $itemskuNumArray = explode(",", $itemskuNum);

                //判断sku跟数量的格式是否一样
                if(count($itemskuArray) <> count($itemskuNumArray)){
                  Db::rollback();
                  $this->error('sku的格式跟数量格式没有一一对应,请重新检查!');
                  return;
                }

                
                
                //判断出库单中，是否包含相同的订单号
                $outInventoryList = $outInventory->where('orderid',$orderid)->select();
                // $sql = $outInventory->getLastSql();
                if(count($outInventoryList)>1){
                  Db::rollback();
                  $this->error(sprintf('订单号:%s,现有出库记录中有重复,请检查!',$orderid));
                  return; 
                }

                for($i=0; $i<count($itemskuArray); $i++){

                  //goods表中的产品
                  $goodItemModel = new GoodsItem();
                  $condition = [];
                  $condition['code'] = trim($itemskuArray[$i]);
                  $goodItem = $goodItemModel->where($condition)->find();

                  if(empty($goodItem)){
                    Db::rollback();
                    $this->error(sprintf('第%s条记录,SKU:%s,产品基础库中不存在或者未入库!',$currentRow,$itemskuArray[$i]));
                    return;    
                  }

                  
                  $balanceCount = $inventoryModel->where('goods_id',$goodItem['id'])->value('balance_count');//剩余库存
                  if(intval($balanceCount)<intval($itemskuNumArray[$i])){
                    $this->error(sprintf('产品SKU:%s,库存不足，请修改库存!',$itemskuArray[$i]));
                    Db::rollback();
                    return false;
                    exit;
                  }

                  //items表中的产品
                  $ItemModel = new Item;
                  $condition = [];
                  $condition['sku'] = trim($itemskuArray[$i]);
                  $item = $ItemModel->where($condition)->find();

                  $detailData = [];
                  $OutInventoryDetail = new OutInventoryDetail();


                  $detailData['id'] = \newId();
                  $detailData['itemsku'] = $itemskuArray[$i];
                  $detailData['itemid'] = $item['id'];
                  $detailData['itemname'] = $item['itemname'];
                  $detailData['goods_id'] = $goodItem['id'];
  
                  $detailData['orderid'] = $orderid;//关联的平台订单号
  
                  $detailData['goods_count'] = $itemskuNumArray[$i]; //申请出库数
                  $detailData['sw_count'] = 0; //已出库数
                  $detailData['left_count'] = $itemskuNumArray[$i]; //未出库数
  
                  $detailData['outid'] = $outid;
                  $detailData['out_orderno'] = $outOrderId;
                  $detailData['warehouseid'] = $warehouseId;
                  $detailData['warehouse_code'] = '1';
  
                  
                  // $detailData['recipients'] = $recipients;
                  $detailData['first_name'] = $firstName;
                  $detailData['last_name'] = $lastName;
                  $detailData['mobile'] = $mobile;
                  $detailData['company'] = $company;
                  
                  //TODO 国家简称需要验证
                  $detailData['state'] = $state;
                  $detailData['province'] = $province;
                  $detailData['city'] = $city;
                  $detailData['postcode'] = $postcode;
                  $detailData['addressone'] = $addressone;
                  $detailData['addresstwo'] = $addresstwo;
                  $detailData['outid'] = $outid;
                  // $detailData['outorderid'] = $outOrderId;
                  
                  $rsDetail = $OutInventoryDetail->save($detailData);
                }


              $rowNo = $rowNo+1;
            }
          Db::commit();
          $this->success();
        } catch (\think\exception\PDOException $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

    }

}
